/**
 * 
 */
package com.effectivsocial.core.jsf.extension;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

/**
 * @author Dhrubo
 * 
 */
public class SpringSecuritExceptionHandlingJsfPhaseListener implements
		PhaseListener {
	private static final transient Logger logger = LoggerFactory
			.getLogger(SpringSecuritExceptionHandlingJsfPhaseListener.class);
	/**
* 
*/
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
	 */
	@Override
	public void afterPhase(PhaseEvent event) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
	 */
	@Override
	public void beforePhase(PhaseEvent event) {
		Exception e = (Exception) FacesContext
				.getCurrentInstance()
				.getExternalContext()
				.getSessionMap()
				.get(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

		logger.debug("Exception - {}", e);

		if (e instanceof BadCredentialsException) {
			FacesContext context = FacesContext.getCurrentInstance();

			context.getExternalContext()
					.getSessionMap()
					.put(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY,
							null);

			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Username or password not valid.", e.getLocalizedMessage());

			context.addMessage(null, message);
		} else if (e instanceof AccessDeniedException) {
			FacesContext context = FacesContext.getCurrentInstance();

			context.getExternalContext()
					.getSessionMap()
					.put(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY,
							null);

			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Session expired or unauthorized access.",
					e.getLocalizedMessage());

			context.addMessage(null, message);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.event.PhaseListener#getPhaseId()
	 */
	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;

	}

}
